package com.ethannhu.todaynews.component.login

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.recyclerview.widget.RecyclerView
import com.ethannhu.repository.DefaultNetworkRepository
import com.ethannhu.super_k.util.StringUtil
import com.ethannhu.todaynews.R
import com.ethannhu.todaynews.component.comment.Comment
import com.ethannhu.todaynews.component.content.Content
import com.ethannhu.todaynews.component.input.InputCodePageData
import com.ethannhu.todaynews.component.user.User
import com.ethannhu.todaynews.entity.response.Meta
import com.ethannhu.todaynews.entity.response.onSuccess
import com.ethannhu.todaynews.model.BaseViewModel
import com.ethannhu.todaynews.util.PreferenceUtil
import com.ethannhu.todaynews.util.SuperRegularUtil
import com.google.firebase.crashlytics.buildtools.reloc.org.apache.http.util.TextUtils
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.launch
import org.apache.commons.lang3.StringUtils
import kotlin.math.log

/**
 * 登录界面 ViewModel，Activity就可以只处理 UI相关的东西了
 */
class LoginViewModel() : BaseViewModel() {
    //成功
    private val _success = MutableLiveData<String>()
    val success: LiveData<String> = _success

    fun login(username: String, password: String) {
        if (StringUtils.isBlank(username)) {
            _tip.value = R.string.enter_phone_or_email
            return
        }

        //如果用户名
        //不是手机号也不是邮箱
        //就是格式错误
        if (!(SuperRegularUtil.isPhone(username) || SuperRegularUtil.isEmail(username))){
            _tip.value = R.string.error_username_format
            return
        }

        if (!StringUtil.isPassword(password)) {
            _tip.value = R.string.enter_password
            return
        }
        val user = User()

        //判断是手机号还有邮箱
        if (SuperRegularUtil.isPhone(username)) {
            //手机号
            user.phone = username
        } else {
            //邮箱
            user.email = username
        }

        user.password = password

        login(user)
    }

    /**
     * 用户名和密码登录，第三方登录
     */
    private fun login(data: User) {
        viewModelScope.launch(coroutineExceptionHandler) {
            DefaultNetworkRepository.login(data).onSuccess(viewModel) {
                //保存用户id
                PreferenceUtil.setUserId(it!!.userId)
                PreferenceUtil.setToken(it!!.session)

                //聊天token
                PreferenceUtil.setChatToken(it!!.chatToken)
                _success.value = it!!.session
            }
        }
    }

    /**
     * 验证码登录
     */
    fun login(data: InputCodePageData) {
        val user = User()
        user.phone = data.phone
        user.email = data.email
        user.code = data.code
        login(user)
    }


}